package com.torry.workflow.service.user.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.torry.workflow.api.user.api.MenuApi;
import com.torry.workflow.api.user.entity.Menu;
import com.torry.workflow.api.user.entity.RoleMenu;
import com.torry.workflow.common.exception.BizException;
import com.torry.workflow.service.user.service.IMenuService;
import com.torry.workflow.service.user.service.IRoleMenuService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@DubboService
@Component
public class MenuFacade implements MenuApi {

    @Resource
    private IMenuService iMenuService;
    @Resource
    private IRoleMenuService iRoleMenuService;
    @Override
    @Transactional
    public void saveMenuInfo(Menu menu) {
        if(menuIsExist(menu)) throw new BizException(400,"重复的菜单名称");
        iMenuService.saveOrUpdate(menu);
    }

    private boolean menuIsExist(Menu menu) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        if(menu.getPid() != null) {
            wrapper.eq("pid", menu.getPid());
        }else {
            wrapper.isNull( "pid");
        }
        Menu menuInfo = iMenuService.getOne(wrapper
                .eq("deleted", 0).eq("name", menu.getName()));
        if (menu.getId() == null) {
            return menuInfo != null;
        }
        return menuInfo != null && !menuInfo.getId().equals(menu.getId());

    }

    @Override
    public List<Menu> getAllMenus() {
        List<Menu> menus = iMenuService.list(new QueryWrapper<Menu>().eq("deleted", 0).isNull("pid").orderByAsc("sort"));
        menus.forEach(menu -> {
            List<Menu> children = iMenuService.list(new QueryWrapper<Menu>()
                    .eq("deleted", 0).eq("pid", menu.getId()).orderByAsc("sort"));
            menu.setChildren(children);
        });
        return menus;
    }

    @Override
    @Transactional
    public void deleteByIds(List<Integer> ids) {
        iMenuService.update(new UpdateWrapper<Menu>().set("deleted", 1).in("id", ids));
        // 移除角色所配置的菜单
        iRoleMenuService.update(new UpdateWrapper<RoleMenu>().in("menu_id", ids));
    }
}
